package com.fouram.rabbitmq;

import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.stereotype.Component;

/**
 * 消息队列发送者
 * @author liup
 */
@Component
@RequiredArgsConstructor
public class MqProducer {

    private final AmqpTemplate rabbitTemplate;

    /**
     * simple简单模式 + work工作模式
     * @param queue
     * @param msgContent
     */
    public void sendSimple(String queue, String msgContent) {
        this.rabbitTemplate.convertAndSend(queue, msgContent);
    }

    /**
     * fanout
     * @param exchange
     * @param msgContent
     */
    public void sendFanout(String exchange, String msgContent) {
        this.rabbitTemplate.convertAndSend(exchange, "", msgContent);
    }

    /**
     * direct
     * @param exchange
     * @param routingKey
     * @param msgContent
     */
    public void sendDirect(String exchange, String routingKey, String msgContent) {
        this.rabbitTemplate.convertAndSend(exchange, routingKey, msgContent);
    }

    /**
     * topic
     * 通配符规则 #：匹配零个或多个单词，*（星号）：匹配不多不少恰好一个单词。
     * @param exchange
     * @param routingKey
     * @param msgContent
     */
    public void sendTopic(String exchange, String routingKey, String msgContent) {
        this.rabbitTemplate.convertAndSend(exchange, routingKey, msgContent);
    }

    /**
     * rpc
     * @param queue
     * @param msgContent
     * @return
     */
    public Object sendRpcAndReceive(String queue, String msgContent) {
        return this.rabbitTemplate.convertSendAndReceive(queue, msgContent);
    }

    /**
     * 延迟队列
     * @param exchange
     * @param routingKey
     * @param msgContent
     * @param delayMilliseconds
     */
    public void sendDelay(String exchange, String routingKey, String msgContent, long delayMilliseconds) {
        this.rabbitTemplate.convertAndSend(exchange,
                routingKey,
                msgContent, message -> {
                    message.getMessageProperties().setHeader("x-delay", delayMilliseconds);
                    return message;
                });
    }

}
